from fastapi import Request
import requests

from service import BinanceService
from common.result.Result import Result
from common.enum import BaseEnum
from common.const import BaseConstant
from util.log import Log


async def GetKLines(req: Request, symbol: str, interval: str, timeZone: int):
    try:
        path = f'{BaseConstant.BASE_URL_PUBLIC}/api/v3/klines'
        params = {
            "symbol": symbol,
            "interval": interval,
            "timeZone": timeZone
        }
        klines = requests.get(url=path, params=params).json()

        # 获取 MACD
        closeList = [float(item[4]) for item in klines]
        MACD = await BinanceService.getMACD(closeList)

        macd = list(MACD.get("MACD"))
        dif = list(MACD.get("DIF"))
        dea = list(MACD.get("DEA"))

        RSI = await BinanceService.getRSI(closeList)
        rsi = list(RSI)

        res = {
            "total": 100,
            "klines": klines[len(klines) - 100 : ],
            "macd": macd[len(macd) - 100 : ],
            "dif": dif[len(dif) - 100 : ],
            "dea": dea[len(dea) - 100 : ],
            "rsi": rsi[len(rsi) - 100 : ]
        }
        return Result.success(res)
    except Exception as e:
        Log.error('获取 K Lines 异常', e)
        return Result.error(BaseEnum.SERVICE_ERROR)
